package com.shanzmoo.admin.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.shanzmoo.admin.util.RedisAdminKeyUtils;
import com.shanzmoo.core.util.RedisCoreKeyUtils;
import com.shanzmoo.db.sys.entity.vo.AddressTreeVo;
import com.shanzmoo.db.sys.service.IAddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 缓存数据管理
 *
 * @author： Gzhao 2021/2/10
 */
@Slf4j
@Component
public class RedisDataManager {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IAddressService addressService;

    /**
     * 地址选择树
     *
     * @return
     * @author Gzhao 2021/2/10
     */
    public List<AddressTreeVo> getAddressTree() {
        String addressTreeKey = RedisAdminKeyUtils.installAddressTreeKey();

        if (!stringRedisTemplate.hasKey(addressTreeKey)) {
            List<AddressTreeVo> data = addressService.getAddressTree();

            List<String> dataStr = data.stream()
                    .map(JSON::toJSONString)
                    .collect(Collectors.toList());

            stringRedisTemplate.delete(addressTreeKey);
            stringRedisTemplate.opsForList().rightPushAll(addressTreeKey, dataStr);
        }
        List<String> valuelist = stringRedisTemplate.opsForList().range(addressTreeKey, 0, -1);

        List<AddressTreeVo> result = valuelist.stream()
                .map(e -> JSON.parseObject(e, AddressTreeVo.class))
                .collect(Collectors.toList());

        return result;
    }
}
